<?php
    /**
    +----------------------------------------------------------
    * 基类文件
    * @author lixiaoping
    +----------------------------------------------------------
    */
class HomeCommonAction extends CommonAction {

	public $user;
	public $uc_members;
	public $ad;
	public $integral;
	public function __construct()
	{	
		parent::__construct();
		 $this->uc_members = M('uc_members');
		 $this->ad = M('web_ad');
		 $this->admin_log = M('web_admin_log');
		 $this->integral = M('web_integral');
		 $this->user = M('web_user');
		 $this->user_info = M('web_user_info');
		 $this->merchanta =  M('web_merchant');
		 $this->integral_setting = M('web_integral_setting');
		$this->common_member = M('pre_common_member');
        $this->member_count = M('pre_common_member_count');
        $this->remind = M('web_remind');
        $this->server_name = $_SERVER['SERVER_NAME'];
		$ads = $this->ad->where('state=1')->select();
		$adar = array();
		foreach ($ads as $adkey => $adv){
			$adar[$adv['labeled']] = $adv['content'];
		}
		$this->assign($adar);
		$this->server = $this->server('d');
        if(!$this->server['c_id'])
        {
        	echo "你访问的地址，无法查询到...";
        }
        $u_id = $this->checkLoginStatus(1,1); //获取登陆用户的id
        $this->assign('usermyid',$u_id);
        $smerchantas = $this->merchanta->where('hot=1')->LIMIT('5')->field('mc_name,u_id')->select();
        $this->assign('s_merchantas',$smerchantas);
        switch (MODULE_NAME){
        	case Bbs:
	        	$this->assign('webdh',4);
	  		break;  
        	case Subject:
	        	$this->assign('webdh',3);
	  		break;  
        	case Exchange:
	        	$this->assign('webdh',2);
	  		break;
	  		default:
	  			$this->assign('webdh',1);
	  		break;
        }
        $remind = $this->remind->where('status=0 AND (u_id='.$u_id.' OR u_id=-1)')->count();
        $this->assign('remindsl',$remind);
	}
	/**
    +----------------------------------------------------------
    * 操作日志
    +----------------------------------------------------------
    */
	public function action_log($log_cat='',$log_obj='',$log_con='',$state=0) {
		$adminid=$this->checkLoginStatus();
		$adminname=$this->checkLoginStatus(1);
	    $data = array (
		    'u_id'			   => $adminid,
	    	'log_user'       => $adminname,
	  		'table_name'  => $log_obj,
		    'log_info'		   => $log_cat,
		    'details'		   => $log_con,
	 	    'log_ip'		   => $this->fj_getIP(),
		    'log_time'	   => time(),
			'status'			   => $state,
		);
		$insertId=$this->admin_log->add($data);
	}
	//删除积分
	public function integralDel($type,$theme_id)
	{
		$uids=$this->integral->where('type='.$type.' AND theme_id='.$theme_id)->find();
		
		$insertId=$this->integral->where(' type='.$uids['type'].' AND theme_id='.$uids['theme_id'])->delete();
		if($insertId<0){
			return '0';
		}else{
			return $uids['u_id'];
		}
	}
	/**
    +----------------------------------------------------------
    * 积分记录
    * @param $uid 会员ID
    * @param $type 积分类型
    +----------------------------------------------------------
    */
	public function integralLog($uid,$type,$theme_id) {
		$integral = $this->integral_setting->where('status=1 AND id='.$type)->find();
	    $data = array (
		    'u_id'			=> $uid,
		    'type'			=> $integral['id'],
		    'score'			=> $integral['score'],
		    'descrip'		=> $integral['item'],
		    'atime'			=> time()
		);
	    if($theme_id>0){
	    	$data['theme_id'] = $theme_id;
	    }
		$insertId=$this->integral->add($data);
		if($insertId) {
			return $insertId;
		} else {
			return false;
		}
	}
    /**
    +----------------------------------------------------------
    * 实时修改变化的用户积分
    +----------------------------------------------------------
    */	
	public function integralLogSum($uid){
				$lists=$this->integral->query("SELECT SUM(score) AS scores,type,u_id FROM `chh_web_integral` WHERE u_id=$uid AND type!=9");
				if(!$lists[0]['scores']){
					$data = array(
						'total_integral'  => 0,
					);				
				}else{
					$data = array(
						'total_integral'  => $lists[0]['scores'],
					);				
				}		     		
		$this->user_info->where('u_id='.$uid)->data($data)->save();
	}
	/*获取用户的身份类型  1:普通用户 2:商户 */
	public function check_user_type($uid){
		$this->user = M('web_user');
		$data = $this->user->field('user_type')->where('u_id ='.$uid)->find();
		return $data['user_type'];
	}

//用户注册处理
	public function user_register($user,$pwd,$mobile,$email,$api='1',$recommend_id='0')
	{
		$regtime = time();//注册时间
		$regip = $this->fj_getIP();
		$uid = uc_user_register($user, $pwd,$email);  //uc完成注册！
		if($uid>1)//注册成功!
		{
			$data4['uid']=$uid;
			$this->member_count->data($data4)->add();
			$data = array('u_id' => $uid,'name' => $user,'password' => md5(md5($pwd)),'role' =>'0','status' => '0','user_type' => '1','recommend_id' => $recommend_id,'home_auth'=>'0','reg_time' => $regtime,'reg_ip'=> $regip,'authority' => '-1','c_id'=>'0');
			$insertId = $this->user->add($data);//写入主网站用户
			
			$data2 = array('u_id' => $uid,'mobile' => $mobile,'email' => $email);
			$user_info = M('web_user_info');
			$insertId = $user_info->data($data2)->add();//写入主网站用户
			if($uid) {
				setcookie('Example_auth', uc_authcode($uid."\t".$user, 'ENCODE'),time()+86400, "/");//注册成功，设置 Cookie，加密直接用 uc_authcode 函数，用户使用自己的函数
				$ucsynlogin = uc_user_synlogin($uid);
				if($api==1){
					cookie('name',$user);
					cookie('login','');
					echo $ucsynlogin;
					//$this->successs('新用户注册成功!'.$ucsynlogin,'/index.php/Home/Member',1);
				}else{
					echo $ucsynlogin;
					return $uid;
				}
			}
		}elseif($uid == -1) {
			echo '<script>alert("用户名不合法");history.go(-1);</script>';
		} elseif($uid == -2) {
			echo '<script>alert("包含要允许注册的词语");history.go(-1);</script>';
		} elseif($uid == -3) {
			echo '<script>alert("用户名已经存在");history.go(-1);</script>';
		} elseif($uid == -4) {
				echo '<script>alert("Email 格式有误");history.go(-1);</script>';
		} elseif($uid == -5) {
				echo '<script>alert("Email 不允许注册");history.go(-1);</script>';
		} elseif($uid == -6) {
			echo '<script>alert("该 Email 已经被注册");history.go(-1);</script>';
		}elseif($uid == -8) {
			echo '<script>alert("该手机号码已经被注册");history.go(-1);</script>';
		} else {
			echo '<script>alert("未定义");history.go(-1);</script>';
		}
		return $uid;
	}
	//登陆处理
	public  function process_login($username , $password  ,$type='uid')
	{
 		list($uid, $username, $password, $email) = uc_user_login($username, $password);//验证帐户和密码
 		if($uid > 0)
 		{
 			setcookie('Example_auth', uc_authcode($uid."\t".$username, 'ENCODE'),time()+86400, "/");
			echo $ucsynlogin = uc_user_synlogin($uid);
			session('userid',$uid);
			cookie('name',$username,time()+86400);
			cookie('Example_auth',uc_authcode($uid."\t".$user, 'ENCODE'),time()+86400);
			cookie('login','');
			return $uid;
		} else {
			return  -9;
			$this->logout('1');
		}
	}

    /**
      +----------------------------------------------------------
     * 检查登录状态
      +----------------------------------------------------------
     */
    //$admn 默认返回登陆的id 1返回id 2返回用户名
    //$type  默认返回用户的id如果 没有登陆返回-1  如果为其他登陆成功返回uid失败直接注销提示登陆
	public function checkLoginStatus($usertype='1',$type='1', $url='1')
	{
		if(!empty($_COOKIE['Example_auth'])) {
			list($Admin_uid, $Admin_username) = explode("\t", uc_authcode($_COOKIE['Example_auth'], 'DECODE'));
		} else {
			$Admin_uid = $Admin_username = '';
		}
		if($Admin_uid>=1)
		{
			if($usertype==1){
				return	$Admin_uid;
			}else{
				return	$Admin_username;
			}
			exit();
		}elseif($type==1){
			return	'-1';
		}else{
			if($url=='1'){
				$this->successs ( '你还没有登录，请先登陆系统', '/index.php/Admin/User/Login',0 );
			}else{
				$this->successs ( '你还没有登录，请先登陆系统', '/index.php/Home/Login/Index',0 );
			}
		}
	}
	/**
    +----------------------------------------------------------
    * 发邮件
    +----------------------------------------------------------
    */	
	public function send_email($title,$message,$mail_server,$mail_to,$mail_from,$mail_user,$mail_password,$mail_port='25')
	{
		include("./include/smtp.class.php");
		date_default_timezone_set("Asia/Shanghai");//设定时区东八区
		$smtpserver = $mail_server;        //SMTP邮件服务器
		$smtpserverport = $mail_port;    //SMTP端口号
		$smtpusermail = $mail_from;     //SMTP发送邮件地址
		$smtpuser = $mail_user;         //SMTP邮件用户
		$smtppass = $mail_password;     //SMTP邮件密码
		$smtpemailto = $mail_to;        //目标邮件地址 发送给谁
		$mailsubject = $title;           //邮件主题
		$mailbody = $message; 			//邮件内容
		$mailtype = "HTML";            //邮件发送方式(HTML/TXT)
		$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);  //这里面的一个true是表示使用身份验证,否则不使用身份验证.
		$smtp->debug = false;                     //是否显示发送的调试信息
		$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
	}
	//找回密码之修改密码
	public function modifyPwd($uid,$newpwd) {
		$uc_membersa = $this->uc_members->where('uid='.$uid)->field('uid , password , salt')->find();
		$md5passa = md5(md5($newpwd).$uc_membersa['salt']);
		$data['password'] = $md5passa;
		$data2['password'] = md5(md5($newpwd));
		$uc_membersb = $this->uc_members->where('uid='.$uid)->save($data);
		//$common_member = $this->common_member->where('uid='.$uid)->save($data);
		$user = $this->user->where('u_id='.$uid)->save($data2);
		if(false !== $uc_membersb && false!==$user){
			echo $ucsynlogout = uc_user_synlogout();
			cookie('name',null);
			cookie('login',null);
			cookie('Example_auth',null);
			cookie(null);
			session(null);
			setcookie('Example_auth', '', -1 , "/");
			unset($_COOKIE);
			unset($_SESSION);
			$this->successs('密码修改成功！你将重新登陆！','/index.php/Home/Login/Index',1);
		}else{
			$this->successs('数据写入错误');
		}
	}
	public function modifyPwdNow($oldpwd,$newpwd,$repwd) {
		$info=$this->checkLoginStatus(1,2);
		$uc_membersa = $this->uc_members->where('uid='.$info)->field('uid , password , salt')->find();
		$md5pass = md5(md5($oldpwd).$uc_membersa['salt']);
	    if($md5pass == $uc_membersa['password']){
	    	if($newpwd!= $repwd){
				$this->successs('新密码两次输入不一样');
				exit();
			}else{
				$md5passa = md5(md5($newpwd).$uc_membersa['salt']);
	            $data['password'] = $md5passa;
	            $data2['password'] = md5(md5($newpwd));
	            //$data3['password'] = md5(md5($newpwd));
	            $uc_membersb = $this->uc_members->where('uid='.$info)->save($data);
	           // $common_member = $this->common_member->where('uid='.$info)->save($data);
	            $user = $this->user->where('u_id='.$info)->save($data2);
	            if(false !== $uc_membersb && false!==$user){
			    	echo $ucsynlogout = uc_user_synlogout();
			    	cookie('name',null);
			    	cookie('login',null);
					cookie('Example_auth',null);
					cookie(null);
					session(null);
					setcookie('Example_auth', '', -1 , "/");
					unset($_COOKIE);
					unset($_SESSION);
	                 $this->successs('密码修改成功！你将重新登陆！','/index.php/Home/Login/Index',1);
	            }else{
	                 $this->successs('数据写入错误');
	            }
			}
	    }else{
	    	$this->successs('原始密码错误');
	    }
	}
	
	//$a 消息标题 $b 消息内容 $c用户id $d发送者 $e 发送状态 $f 发送时间
	public function fj_remind($a,$b='',$c='0',$d='系统',$e='0',$f='0'){
		if($f==0){
			$data['time'] = time();
		}else{
			$data['time'] = $f;
		}
		if($c==0){
			$data['u_id'] = $this->checkLoginStatus(1,1); //获取登陆用户的id
		}else{
			$data['u_id'] = $c;
		}
		$data['status'] = $e;
		$data['name'] = $a;
		$data['nr'] = $b;
		$data['type'] = $d;
		$remind = $this->remind->data($data)->add();
		return $remind;
	}
}